//
//  YEventDTableViewController.m
//  shijianpinggu
//
//  Created by apple on 2017/3/30.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "YEventDTableViewController.h"
#import "YEventInforMTTableViewCell.h"
#import "YEventDeTableViewCell.h"
#import "MIPhotoBrowser.h"
#import "MIBrowserImageView.h"

#define UILABEL_LINE_SPACE 6

#define HEIGHT [ [ UIScreen mainScreen ] bounds ].size.height

@interface YEventDTableViewController ()<MIPhotoBrowserDelegate>
@property(nonatomic,strong)NSArray *arrayName;
@property(nonatomic,strong)NSArray *arrayInfo;
@property(nonatomic,strong)NSArray *imageAr;

@property(nonatomic,strong)NSDictionary *dicInfo;

@property(nonatomic,strong)NSMutableArray *cellHeighAr;

@property(nonatomic,assign)NSInteger cellHeigh;


@property(nonatomic,strong)UIView *countView;

@end

@implementation YEventDTableViewController
-(NSMutableArray *)cellHeighAr{
    if (!_cellHeighAr) {
        self.cellHeighAr = [NSMutableArray new];
    }
    return _cellHeighAr;
}
-(NSArray *)arrayInfo{
    if (!_arrayInfo) {
        self.arrayInfo = [NSArray new];
    }
    return _arrayInfo;
}

-(NSArray *)imageAr{
    if (!_imageAr) {
        self.imageAr = [NSArray new];
    }
    return _imageAr;
}




- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"检测详情";
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    
    //去掉返回按钮上的文字
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"YEventInforMTTableViewCell" bundle:nil] forCellReuseIdentifier:@"eventIfCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"YEventDeTableViewCell" bundle:nil] forCellReuseIdentifier:@"eventDeCell"];
    self.dicInfo = [NSDictionary new];
    self.cellHeigh = 0;
    
    self.tableView.showsVerticalScrollIndicator = NO;
//    self.arrayName = [[NSArray alloc] initWithObjects:@"网站域名：",@"漏洞URL：",@"漏洞类型：",@"漏洞风险等级：",@"漏洞描述：",@"漏洞截图：", nil];
    
    self.arrayInfo = [[NSArray alloc] initWithObjects:@"易魔方官网",@"http://www.emof.net",@"外链",@"高危",@"网站存在外链漏洞，外链地址为。。",@"", nil];

//    self.iamgeAr = [[NSArray alloc] initWithObjects:@"wo_nnn",@"ttt_bbb",@"ddddd",@"wo_nnn", @"wo_nnn",@"ttt_bbb",nil];
    
     self.countView = [UIView new];
    
     [self loadDataFormUrl];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [self.tableView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return 5;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.row < 4) {
        YEventInforMTTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"eventIfCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.name.text = self.arrayName[indexPath.row];
       
        switch (indexPath.row) {
            case 0:
                cell.informotion.text = self.dicInfo[@"site"];                break;
            case 1:
                cell.informotion.text = self.dicInfo[@"type_value"];
                break;
            case 2:
                cell.informotion.text = self.dicInfo[@"descrip"];
                break;
            case 3:
                cell.informotion.text = @"";

            
                
            default:
                break;
        }

        

        //设置字间距 NSKernAttributeName:@1.5f
//        CGRect newSize = [cell.informotion.text boundingRectWithSize:CGSizeMake(cell.informotion.frame.size.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil];
//        CGRect newSizeOneLine = [@"得到一行文字的高度" boundingRectWithSize:CGSizeMake(cell.informotion.frame.size.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil];
//        NSInteger cellHeighOneLine = newSizeOneLine.size.height;
//        NSInteger cellHeigh = newSize.size.height;
//        NSLog(@"%ld",(long)cellHeighOneLine);
//        NSLog(@"%ld",(long)cellHeigh);

        
        if (cell.informotion.text==nil) {
             
        }else{
            [self setLabelSpace:cell.informotion withValue:cell.informotion.text withFont: [UIFont systemFontOfSize:14] ];
        }
        CGFloat width;
        if ([UIScreen mainScreen].bounds.size.width == 414) {
             width = 315.333;
        }else if([UIScreen mainScreen].bounds.size.width == 375){
             width = 276.5;
        }else{
             width = 220;
        }
        
        CGFloat  cellHeigh = [self getSpaceLabelHeight:cell.informotion.text withFont: [UIFont systemFontOfSize:14] withWidth:width];
        CGFloat cellHeighOneLine = [self getSpaceLabelHeight:@"一行高度" withFont: [UIFont systemFontOfSize:14] withWidth:width];
        NSLog(@"fffffffffffffff%f",cell.informotion.frame.size.width);
        if (cellHeigh > cellHeighOneLine) {
            self.cellHeigh =   50+cellHeigh-cellHeighOneLine ;
            
        }else{
            self.cellHeigh = 50;
        }
        

       
        
        return cell;
    }else if(indexPath.row == 4){
        YEventDeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"eventDeCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
//        [cell imageArWitharrray:self.iamgeAr];
        
       
        self.countView.frame = cell.countView.frame;
        
        NSInteger width = (cell.frame.size.width-5*4)/3;
        NSInteger heigh = 100;
                for (int i=0; i<self.imageAr.count; i++) {
            UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(i*width+5*(i+1), 0, width, heigh)];
            
            [imageV sd_setImageWithURL:[NSURL URLWithString:self.imageAr[i]] placeholderImage:[UIImage imageNamed:@"jiazai"]];
//            imageV.backgroundColor = [UIColor redColor];
            
            
            imageV.userInteractionEnabled = YES;
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
            [imageV addGestureRecognizer:tap];
            imageV.tag = i;
            
            [cell.countView addSubview:imageV];
          
        }
        cell.scrollView.pagingEnabled = YES;
        cell.viewWidth.constant = (self.imageAr.count)*(width)+(self.imageAr.count+1)*5;
        
        self.countView = cell.countView;
        return cell;
    }else{
        YEventDeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"eventDeCell" forIndexPath:indexPath];
        cell.imageAr = [NSMutableArray new];
        [cell.imageAr addObjectsFromArray:self.imageAr];
        return cell;
    }
    
    
}

-(void)setLabelSpace:(UILabel*)label withValue:(NSString*)str withFont:(UIFont*)font {
    
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    
    paraStyle.alignment = NSTextAlignmentLeft;
    
    paraStyle.lineSpacing = UILABEL_LINE_SPACE; //设置行间距
    
    paraStyle.hyphenationFactor = 1.0;
    
    paraStyle.firstLineHeadIndent = 0.0;
    
    paraStyle.paragraphSpacingBefore = 0.0;
    
    paraStyle.headIndent = 0;
    
    paraStyle.tailIndent = 0;
    
    //设置字间距 NSKernAttributeName:@1.5f
    
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f
                          };
    
    
    
    NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:str attributes:dic];
    
    label.attributedText = attributeStr;
    
}

//计算UILabel的高度(带有行间距的情况)

-(CGFloat)getSpaceLabelHeight:(NSString*)str withFont:(UIFont*)font withWidth:(CGFloat)width {
    
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    
    paraStyle.alignment = NSTextAlignmentLeft;
    
    paraStyle.lineSpacing = UILABEL_LINE_SPACE;
    
    paraStyle.hyphenationFactor = 1.0;
    
    paraStyle.firstLineHeadIndent = 0.0;
    
    paraStyle.paragraphSpacingBefore = 0.0;
    
    paraStyle.headIndent = 0;
    
    paraStyle.tailIndent = 0;
    
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f
                          };
    CGSize size = [str boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    
    return size.height;
    
}

-(NSInteger)labelHeighWhith:(NSString *)sender{
    
    CGRect newSize = [sender boundingRectWithSize:CGSizeMake(200, [UIScreen mainScreen].bounds.size.width) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil];
    NSInteger cellHeigh = newSize.size.height;
    //        [self.cellHeighAr addObject:[NSString stringWithFormat:@"%ld",(long)cellHeigh]];
    
    return cellHeigh;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row < 4) {
        
        return self.cellHeigh;
    }else {
        
        return 100;
    }
}
- (void)tapAction:(UIGestureRecognizer *)gesture {
    UIImageView *imageView = (UIImageView *)gesture.view;
    NSLog(@"image view = %@", imageView);
    NSLog(@"count view = %@", self.countView);
    MIPhotoBrowser *photoBrowser = [[MIPhotoBrowser alloc] init];
    photoBrowser.delegate = self;
    photoBrowser.sourceImagesContainerView = self.countView;
    photoBrowser.imageCount = self.imageAr.count;
    photoBrowser.currentImageIndex = imageView.tag;
    [photoBrowser show];
    NSLog(@"tap action   tag = %ld", (long)imageView.tag);
}

- (UIImage *)photoBrowser:(MIPhotoBrowser *)photoBrowser placeholderImageForIndex:(NSInteger)index {
    NSLog(@"photobrowser index = %ld", (long)index);
    UIImageView *imageView = self.countView.subviews[index];
    return imageView.image;
}

//请求数据
-(void)loadDataFormUrl{
    
    
    NSDictionary *parameter = @{@"type_v":self.type_v,@"type_id":self.type_id};
    
    //    NSLog(@"%@",dict);
    
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // post请求
    [manager POST:@"http://wangan.ldynet.cn/index.php/IndexApp/Api_list_detail" parameters:parameter constructingBodyWithBlock:^(id  _Nonnull formData) {
        // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 这里可以获取到目前的数据请求的进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 请求成功，解析数据
        
        //        NSData *jsonData = [responseObject dataUsingEncoding:NSUTF8StringEncoding];
        //
        //        NSError *err;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSLog(@"aaaaaaaa%@", dic);
        
        self.dicInfo = dic[@"data"];
        
        self.imageAr = dic[@"data"][@"image"];
        
        NSLog(@"%@", self.imageAr);
        
        self.arrayName = [[NSArray alloc] initWithObjects:@"网站域名:",@"事件分类:",@"事件描述:",@"漏洞截图:", nil];
        [self.tableView reloadData];
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 请求失败
        // [self alertWithString:@"请稍后再试"];
    }];
    
    
    //[self loginUrl];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
